#define _CRT_SECURE_NO_WARNINGS 1
int dx[] = { 0,0,1,-1 };
int dy[] = { 1,-1,0,0 };
int m = 0, n = 0;
class Solution {
public:
    bool Rot(vector<vector<int>>& grid)
    {
        bool ret = false;
        vector<vector<bool>> visit(m, vector<bool>(n, false));
        for (int i = 0;i < m;++i)
        {
            for (int j = 0;j < n;++j)
            {
                if (visit[i][j] == true || grid[i][j] == 1 || grid[i][j] == 0)
                {
                    continue;
                }
                for (int k = 0;k < 4;++k)
                {
                    int a = i + dx[k], b = j + dy[k];
                    if (a >= 0 && a < m && b >= 0 && b < n && grid[a][b] == 1)
                    {
                        grid[a][b] = 2;
                        visit[a][b] = true;
                        ret = true;
                    }
                }
            }
        }
        return ret;
    }
    int orangesRotting(vector<vector<int>>& grid)
    {
        m = grid.size(), n = grid[0].size();
        int count = 0;
        while (Rot(grid))
        {
            ++count;
        }
        for (int i = 0;i < m;++i)
        {
            for (int j = 0;j < n;++j)
            {
                if (grid[i][j] == 1)
                {
                    return -1;
                }
            }
        }
        return count;
    }
};